package cn.wenhe9.novel.config;

import cn.wenhe9.novel.constant.CacheConsts;
import cn.wenhe9.novel.json.searializer.FastJsonRedisSerializer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 缓存配置类
 *
 * @author DuJinliang
 * 2022/5/18
 */
@Configuration
public class CacheConfig {
    /**
     * Redis 缓存管理器
     */
    @Bean
    public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory){

        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);

        //对不同的缓存空间设置不同的过期时间，处理缓存雪崩问题
        //配置序列化(解决乱码的问题),允许缓存空值，处理缓存穿透问题
        Map<String, RedisCacheConfiguration> cacheMap = new LinkedHashMap<>(CacheConsts.CacheEnum.values().length);
        for (CacheConsts.CacheEnum c : CacheConsts.CacheEnum.values()) {
            cacheMap.put(c.getName(), RedisCacheConfiguration.defaultCacheConfig().disableCachingNullValues()
                            .prefixCacheNameWith(CacheConsts.REDIS_CACHE_PREFIX)
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)));
        }

        RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
                .withInitialCacheConfigurations(cacheMap)
                .build();

        return cacheManager;
    }

}
